package com.qdhh.enrollment.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qdhh.enrollment.common.BusinessException;
import com.qdhh.enrollment.mapper.AdminUserMapper;
import com.qdhh.enrollment.model.AdminUser;
import com.qdhh.enrollment.service.AdminService;
import com.qdhh.enrollment.service.dto.AdminLoginResult;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 管理员服务实现类
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminUserMapper, AdminUser> implements AdminService {

    @Override
    public AdminLoginResult login(String username, String password) {
        if (!StringUtils.hasText(username) || !StringUtils.hasText(password)) {
            throw new BusinessException("用户名和密码不能为空");
        }

        // 查询管理员用户
        LambdaQueryWrapper<AdminUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdminUser::getUsername, username)
                .eq(AdminUser::getDeleted, 0);
        AdminUser admin = getOne(queryWrapper);

        if (admin == null) {
            throw new BusinessException("用户名或密码错误");
        }

        // 检查状态
        if (admin.getStatus() == null || admin.getStatus() == 0) {
            throw new BusinessException("账号已被禁用");
        }

        // 验证密码（兼容MD5和BCrypt）
        boolean passwordValid = false;
        String passwordHash = admin.getPasswordHash();
        
        if (passwordHash != null) {
            // 如果是BCrypt加密
            if (passwordHash.startsWith("$2a$") || passwordHash.startsWith("$2b$")) {
                passwordValid = BCrypt.checkpw(password, passwordHash);
            } else {
                // MD5加密（兼容旧数据）
                String md5Hash = cn.hutool.crypto.digest.DigestUtil.md5Hex(password);
                passwordValid = md5Hash.equalsIgnoreCase(passwordHash);
            }
        }

        if (!passwordValid) {
            throw new BusinessException("用户名或密码错误");
        }

        // 使用Sa-Token登录，指定loginId为admin_前缀的管理员ID
        String loginId = "admin_" + admin.getId();
        StpUtil.login(loginId);
        String token = StpUtil.getTokenValue();

        return AdminLoginResult.builder()
                .token(token)
                .admin(admin)
                .build();
    }

    @Override
    public AdminUser getCurrentAdmin() {
        // 获取当前登录的管理员ID
        if (!StpUtil.isLogin()) {
            throw new BusinessException("未登录");
        }

        String loginId = StpUtil.getLoginIdAsString();
        if (!loginId.startsWith("admin_")) {
            throw new BusinessException("非管理员账号");
        }

        Long adminId = Long.parseLong(loginId.substring(6));
        AdminUser admin = getById(adminId);
        
        if (admin == null || (admin.getDeleted() != null && admin.getDeleted() == 1)) {
            throw new BusinessException("管理员不存在");
        }

        return admin;
    }

    @Override
    public void logout() {
        StpUtil.logout();
    }
}

